﻿using DataAccessLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text.RegularExpressions;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace Account
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class AddRecord : Page
    {
        public AddRecord()
        {
            this.InitializeComponent();
        }

        private void OnKeyboardButton_Click(object sender, RoutedEventArgs e)
        {
            this.result.Text = this.result.Text == "0.00" ? "" : this.result.Text;
            this.result.Text += (e.OriginalSource as Button).Content as string;
        }

        private void OnBackspaceButton_Click(object sender, RoutedEventArgs e)
        {
            this.result.Text = this.result.Text.Substring(0, this.result.Text.Length - 1);
        }

        private void OnPlusOrMinusButton_Click(object sender, RoutedEventArgs e)
        {
            var expression = this.result.Text;
            if (expression.EndsWith('+') || expression.EndsWith('-'))
                return;
            if (new Regex(@"^\d+[\+\-]\d+").IsMatch(expression))
            {
                if (expression.Contains("+"))
                {
                    var nums = expression.Split("+");
                    this.result.Text = (Double.Parse(nums[0]) + Double.Parse(nums[1])).ToString();
                }
                else if (expression.Contains("-"))
                {
                    var nums = expression.Split("-");
                    var sum = Double.Parse(nums[0]) - Double.Parse(nums[1]);
                    sum = sum < 0 ? 0 : sum;
                    this.result.Text = sum.ToString();
                }
            }
            var symbol = (sender as Button).Content as string;
            
            this.result.Text += symbol;
        }

        private void OnCompleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.ConsumeTypeGridView.SelectedItem != null)
            {
                var record = new ConsumeRecord()
                {
                    Type = this.ConsumeTypeGridView.SelectedItem.ToString(),
                    Value = (float)(Double.Parse(this.result.Text)),
                    Date = new DateTime(2018,8,14).Date//DateTime.Now.Date
                };
                DataAccess.AddData(record);
                MainPage.ContentFrame.Navigate(typeof(Details));
            }
        }
    }
}
